package supervalue

import (
	"bufio"
	"bytes"
	"encoding/csv"
	"encoding/json"
	"fmt"
	"math"
	"os"
	"reflect"
	"regexp"
	"sort"
	"strconv"
	"strings"
	"sync"
	"time"
	"unicode"
	"unicode/utf8"
)

type SuperValue struct {
	Kys    []string     //存储键
	KObj   []KvData     //对象
	kArray []SuperValue //数组
	Value  interface{}  //常规类型
	Path   Path         //上级指针
	Type   string
	Cache  bool //是否启用缓存
}

// 新版本结构调整
//
//	type SuperValue2 struct {
//		Type   int             //当前类型,使用int区分类型,便于判断优先级
//		Value  interface{}     //存储除引用类型的其他类型
//		KArray []SuperValue2   //存储数组
//		Kys    []string        //与KObj为对应关系,方便Karray与Kobj的互相转化
//		KObj   []SuperValue2   //仅存储所有的键值
//		path   *SuperValue2    //舍弃原来的位置关系，仅保留上级
//	}
var (
	ValueCachePool sync.Pool
	valueCache     []*SuperValue
	CacheNum       int32
)

const (
	ObjV  = "object"
	ArrV  = "array"
	NumV  = "number"
	StrV  = "string"
	BoolV = "bool"
)

type KvData struct {
	Key string
	Val SuperValue
}
type Path struct {
	Superior *SuperValue
	Index    int
	Key      string
}

func (this *SuperValue) blank(gread int) string {
	str := " "
	for i := 0; i < gread; i++ {
		str += " "
	}
	return str
}

func (this *SuperValue) String() string {
	return this.AddBlank(0)
}

func (this *SuperValue) AddBlank(i int) string {
	if this.Type == ObjV { //对象不为0
		str := " {\n"
		for _, v := range this.KObj {
			if v.Val.Type == StrV {
				str += fmt.Sprintf("  \"%s\":\"%s\",\n", this.DecodeStr(v.Key), this.DecodeStr(v.Val.AddBlank(i+1)))
			} else if v.Val.Type == ArrV || v.Val.Type == ObjV {
				str += fmt.Sprintf("  \"%s\":%s,\n", this.DecodeStr(v.Key), v.Val.AddBlank(i+1))
			} else {
				str += fmt.Sprintf("  \"%s\":%s,\n", this.DecodeStr(v.Key), this.DecodeStr(v.Val.AddBlank(i+1)))
			}
		}
		str = strings.TrimSuffix(str, ",\n") + fmt.Sprintf("\n %s}", this.blank(i))
		return str
	} else if this.Type == ArrV {
		str := "[\n"
		for _, v := range this.kArray {
			if v.Type == StrV {
				str += fmt.Sprintf("\"%s\",\n", this.DecodeStr(v.AddBlank(i+1)))
			} else if v.Type == ArrV || v.Type == ObjV {
				str += fmt.Sprintf("%s,\n", v.AddBlank(i+1))
			} else {
				str += fmt.Sprintf("%s,\n", this.DecodeStr(v.AddBlank(i+1)))
			}
		}
		str = strings.TrimSuffix(str, ",\n")
		str += fmt.Sprintf("\n %s]", this.blank(i))
		return str
	} else if this.Value != nil {
		switch k := this.Value.(type) {
		case string:
			return fmt.Sprintf("%s", k)
		default:
			return fmt.Sprintf("%v", k)
		}
	} else {
		return ""
	}
}
func NewSVArray() *SuperValue {
	return &SuperValue{Path: Path{}, Type: ArrV} //初始化
}
func NewSVObject() *SuperValue {
	return &SuperValue{Path: Path{}, Type: ObjV}
}
func (this *SuperValue) SetKeyValues(arg ...interface{}) *SuperValue {
	if len(arg)%2 != 0 {
		fmt.Println("Kv必须为双数")
		return this
	}
	for i := 0; i < len(arg); {
		this.SetKeyValue(arg[i].(string), arg[i+1])
		i += 2
	}
	return this
}

// 创建一个键值并返回该键值指向的对象
func (this *SuperValue) ForceByPath(path string) *SuperValue {
	this.Type = ObjV
	this.SetKeyValue(path, NewSVObject())
	return this.ValueByName(path)
}

// 使用任意变量初始化一个supervalue,结构体中未暴露的字段将不会被映射
func (this *SuperValue) SetValue(val interface{}) *SuperValue {
	this.Clear()
	//处理指针
	vi := reflect.ValueOf(val)     //获取值
	for vi.Kind() == reflect.Ptr { //如果值的类型为指针
		vi = vi.Elem() //将其转化为非指针类型
	}
	if !vi.IsValid() {
		fmt.Println("无效指针")
		return this
	}
	val = vi.Interface()
	switch s := val.(type) {
	case int, float64, int32, int64, float32, uint, uint8, uint16, uint32, uint64:
		this.Type = NumV
		this.Value = s
	case time.Time:
		this.Type = StrV
		this.Value = s.Format("2006-01-02 15:04:05")
	case bool:
		this.Value = s
		this.Type = BoolV
	case SuperValue:
		*this = s
	case string:
		this.Type = StrV
		this.Value = s
	case nil:
	default:
		this.setObjValue(val)
	}
	return this
}
func (this *SuperValue) setObjValue(val interface{}) {
	v := reflect.ValueOf(val)

	for v.Kind() == reflect.Ptr {
		v = v.Elem() //如果为指针则获取原值,然后进行判断
	}
	if v.Kind() == reflect.Array || v.Kind() == reflect.Slice {
		for i := 0; i < v.Len(); i++ {
			this.ArrayAppendValue(v.Index(i).Interface())
		}
	} else if v.Kind() == reflect.Map {
		keys := v.MapKeys()
		for _, key := range keys {
			value := v.MapIndex(key) //值
			//创建一个array
			value.Interface()
			this.SetKeyValue(fmt.Sprintf("%v", key.Interface()), value.Interface())
		}
	} else if v.Kind() == reflect.Struct {
		typ := v.Type()
		for i := 0; i < v.NumField(); i++ {
			field := v.Field(i)
			filedName := typ.Field(i).Name
			if unicode.IsLower([]rune(filedName)[0]) {
				fmt.Println("不可读取的变量：", filedName)
				continue
			}
			this.SetKeyValue(filedName, field.Interface())
		}
	} else {
		this.Type = StrV
		this.Value = fmt.Sprintf("%v", val)
	}
}

// 设置键值，除函数等特殊类型均支持
func (this *SuperValue) SetKeyValue(key string, val interface{}) *SuperValue {
	//defer lock.Unlock()
	//lock.Lock()
	//先处理指针
	vi := reflect.ValueOf(val)     //获取值
	for vi.Kind() == reflect.Ptr { //如果值的类型为指针
		vi = vi.Elem() //将其转化为非指针类型
	}
	if !vi.IsValid() { //如果为nil    //val一定不为指针
		fmt.Println("无效的值")
		return this
	}
	val = vi.Interface()
	this.Type = ObjV
	switch s := val.(type) {
	case int, float64, int32, int64, float32, uint, uint8, uint16, uint32, uint64:
		this.setInterfaceValue(key, s)
	//case *int:
	//	this.setInterfaceValue(key, *s)
	//case *float64:
	//	this.setInterfaceValue(key, *s)
	//case *int32:
	//	this.setInterfaceValue(key, *s)
	//case *int64:
	//	this.setInterfaceValue(key, *s)
	//case *float32:
	//	this.setInterfaceValue(key, *s)
	//case *uint:
	//	this.setInterfaceValue(key, *s)
	//case *uint8:
	//	this.setInterfaceValue(key, *s)
	//case *uint16:
	//	this.setInterfaceValue(key, *s)
	//case *uint32:
	//	this.setInterfaceValue(key, *s)
	//case *uint64:
	//	this.setInterfaceValue(key, s)
	case time.Time:
		this.setInterfaceValue(key, s.Format("2006-01-02 15:04:05"))
	case bool:
		this.setBoolValue(key, s)
	//case *bool:
	//	this.setBoolValue(key, *s)
	case SuperValue:
		//将所有的上级针重新排列
		this.setSuperValue(key, s)
	//case *SuperValue:
	//	this.setSuperValue(key, *s)
	case string:
		this.setStringValue(key, s)
	//case *string:
	//	this.setStringValue(key, *s)
	case nil:

	default: //数组，map或结构体
		this.setOtherValue(key, s)
	}
	this.ValueByName(key).Path = Path{
		this, -1, key,
	}
	return this
}

// 如果是一个数组，如果是一个结构体，如果是一个map
func (this *SuperValue) setOtherValue(key string, val interface{}) {

	v := reflect.ValueOf(val)
	this.SetKeyValue(key, NewSVObject())
	now := this.ValueByName(key)
	for v.Kind() == reflect.Ptr {
		v = v.Elem() //如果为指针则获取原值,然后进行判断
	}
	if v.Kind() == reflect.Array || v.Kind() == reflect.Slice {

		for i := 0; i < v.Len(); i++ {
			now.ArrayAppendValue(v.Index(i).Interface())
		}
	} else if v.Kind() == reflect.Map {
		keys := v.MapKeys()
		for _, ky := range keys {
			value := v.MapIndex(ky) //值
			//创建一个array
			value.Interface()
			now.SetKeyValue(fmt.Sprintf("%v", ky.Interface()), value.Interface())
		}
	} else if v.Kind() == reflect.Struct {
		typ := v.Type()
		for i := 0; i < v.NumField(); i++ {
			field := v.Field(i)
			filedName := typ.Field(i).Name
			if unicode.IsLower([]rune(filedName)[0]) {
				fmt.Println("不可读取的变量：", filedName)
				continue
			}
			now.SetKeyValue(filedName, field.Interface())
		}
	} else {
		//其他均以string类型保存
		now.SetValue(fmt.Sprintf("%v", val))
	}
}

func (this *SuperValue) setBoolValue(key string, val bool) *SuperValue {
	//如果已经存在该键值，则修改原来的值,否则追加
	if index := InArray(this.Kys, key); index != -1 { //存在,需要修改原值
		this.KObj[index].Val = SuperValue{
			Value: val, Type: BoolV,
		}
	} else {
		this.Kys = append(this.Kys, key) //不存在，需要增加原值
		this.KObj = append(this.KObj, KvData{
			key, SuperValue{
				Value: val, Type: BoolV,
			},
		})
	}
	return this
}

func (this *SuperValue) setStringValue(key string, val string) *SuperValue {
	//如果已经存在该键值，则修改原来的值,否则追加
	if index := InArray(this.Kys, key); index != -1 { //存在,需要修改原值
		this.KObj[index].Val = SuperValue{
			Value: val, Type: StrV,
		}
	} else {
		this.Kys = append(this.Kys, key) //不存在，需要增加原值
		this.KObj = append(this.KObj, KvData{
			key, SuperValue{
				Value: val, Type: StrV,
			},
		})
	}
	return this
}

func (this *SuperValue) setInterfaceValue(key string, val interface{}) *SuperValue {
	//如果已经存在该键值，则修改原来的值,否则追加
	if index := InArray(this.Kys, key); index != -1 { //存在,需要修改原值
		this.KObj[index].Val = SuperValue{
			Value: val, Type: NumV,
		}
	} else {
		this.Kys = append(this.Kys, key) //不存在，需要增加原值
		this.KObj = append(this.KObj, KvData{
			key, SuperValue{
				Value: val, Type: NumV,
			},
		})
	}
	return this
}

func (this *SuperValue) setSuperValue(key string, val SuperValue) *SuperValue {
	val.Path.Superior = this //将最外层对象的指针指向将要加入的对象
	//无论是修改键值还是修改数组值均会影响到原数值，故不影响结果，无需调整
	//内层对象暂无较好的处理方式
	if index := InArray(this.Kys, key); index != -1 { //存在,需要修改原值
		this.KObj[index].Val = val
	} else {
		this.Kys = append(this.Kys, key) //不存在，需要增加原值
		this.KObj = append(this.KObj, KvData{
			key, val,
		})

	}
	return this
}
func InArray(arr []string, str string) int {
	for i, v := range arr {
		if v == str {
			return i
		}
	}
	return -1
}
func (this *SuperValue) SetIndexValue(index int, val interface{}) *SuperValue {
	//defer lock.Unlock()
	//lock.Lock()
	this.Type = ArrV
	vi := reflect.ValueOf(val)
	for vi.Kind() == reflect.Ptr {
		vi = vi.Elem()
	}
	if !vi.IsValid() {
		return this
	}
	val = vi.Interface()
	switch s := val.(type) {
	//case *SuperValue:
	//	this.setIndexSuper(index, *s)
	case SuperValue:
		this.setIndexSuper(index, s)
	case int, float64, int32, int64, float32, uint, uint8, uint16, uint32, uint64:
		this.setIndexInterface(index, s)
	case time.Time:
		this.setIndexInterface(index, s.Format("2006-01-02 15:04:05"))
	//case *int:
	//	this.setIndexInterface(index, *s)
	//case *float64:
	//	this.setIndexInterface(index, *s)
	//case *int32:
	//	this.setIndexInterface(index, *s)
	//case *int64:
	//	this.setIndexInterface(index, *s)
	//case *float32:
	//	this.setIndexInterface(index, *s)
	//case *uint:
	//	this.setIndexInterface(index, *s)
	//case *uint8:
	//	this.setIndexInterface(index, *s)
	//case *uint16:
	//	this.setIndexInterface(index, *s)
	//case *uint32:
	//	this.setIndexInterface(index, *s)
	//case *uint64:
	//	this.setIndexInterface(index, *s)
	case bool:
		this.setIndexBool(index, s)
	//case *bool:
	//	this.setIndexBool(index, *s)
	case string:
		this.setIndexString(index, s)
	//case *string:
	//	this.setIndexString(index, *s)
	//case json.Number:
	//	f, _ := s.Float64()
	//	this.setIndexInterface(index, f)
	case nil:

	default:
		//map struct array
		this.setIndexOther(index, s)
	}
	this.ValueByIndex(index).Path = Path{
		this, index, "",
	}
	return this
}

// 数组 v.index  map v.mapkeys []   mapindex    struct v.type v.field
func (this *SuperValue) setIndexOther(index int, val interface{}) {
	this.SetIndexValue(index, NewSVObject())
	now := this.ValueByIndex(index)
	v := reflect.ValueOf(val)
	//for v.Kind() == reflect.Ptr { //如果v是一个指针
	//	v = v.Elem()
	//}
	if v.Kind() == reflect.Array || v.Kind() == reflect.Slice {
		for i := 0; i < v.Len(); i++ {
			now.ArrayAppendValue(v.Index(i).Interface())
		}
	} else if v.Kind() == reflect.Map {
		keys := v.MapKeys()
		for _, key := range keys {
			value := v.MapIndex(key) //值
			//创建一个array
			value.Interface()
			now.SetKeyValue(fmt.Sprintf("%v", key.Interface()), value.Interface())
		}
	} else if v.Kind() == reflect.Struct {
		typ := v.Type()
		for i := 0; i < v.NumField(); i++ {
			field := v.Field(i)
			filedName := typ.Field(i).Name
			if unicode.IsLower([]rune(filedName)[0]) {
				fmt.Println("不可读取的变量：", filedName)
				continue
			}
			now.SetKeyValue(filedName, field.Interface())
		}
	} else {
		now.SetValue(fmt.Sprintf("%v", val))
	}
}

// 设置布尔类型的值
func (this *SuperValue) setIndexBool(index int, val bool) *SuperValue {
	if len(this.kArray) <= index {
		for i := 0; i <= index+1-len(this.kArray); i++ {
			this.kArray = append(this.kArray, *NewSVObject()) //增加零值
		}
	}
	this.kArray[index] = SuperValue{
		Value: val, Type: BoolV,
	}
	return this
}

// 先转化为字符串,然后通过字符串函数进行转化
func (this *SuperValue) Int() int {
	res, err := strconv.Atoi(this.String())
	if err != nil {
		fmt.Errorf(err.Error())
		return 0
	}
	return res
}

func (this *SuperValue) Int8ByByName(key string, def int8) int8 {
	s := this.ValueByName(key)
	if s == nil {
		return def
	}
	return s.Int8()
}

func (this *SuperValue) AsArrayList() []string { //将数组转化为列表形式
	res := []string{}
	this.Range(func(key string, val *SuperValue) bool {
		res = append(res, val.String())
		return true
	})
	return res
}
func (this *SuperValue) AsIntList() []int {
	var res []int
	this.Range(func(key string, val *SuperValue) bool {
		res = append(res, val.Int())
		return true
	})
	return res
}
func (this *SuperValue) setIndexInt(index int, val int) *SuperValue {
	//如果当前切片的长度小于指定的长度,则扩容原切片，否则直接设定值
	if len(this.kArray) <= index {
		for i := 0; i <= index+1-len(this.kArray); i++ {
			this.kArray = append(this.kArray, *NewSVObject()) //增加零值
		}
	}
	this.kArray[index] = SuperValue{
		Value: val,
	}
	return this
}
func (this *SuperValue) setIndexString(index int, val string) *SuperValue {
	//如果当前切片的长度小于指定的长度,则扩容原切片，否则直接设定值
	if len(this.kArray) <= index {
		for i := 0; i <= index+1-len(this.kArray); i++ {
			this.kArray = append(this.kArray, *NewSVObject()) //增加零值
		}
	}
	this.kArray[index] = SuperValue{
		Value: val, Type: StrV,
	}
	return this
}
func (this *SuperValue) setIndexInterface(index int, val interface{}) *SuperValue {
	//如果当前切片的长度小于指定的长度,则扩容原切片，否则直接设定值
	if len(this.kArray) <= index {
		for i := 0; i <= index+1-len(this.kArray); i++ {
			this.kArray = append(this.kArray, *NewSVObject()) //增加零值
		}
	}
	this.kArray[index] = SuperValue{
		Value: val, Type: NumV,
	}
	return this
}
func (this *SuperValue) setIndexSuper(index int, val SuperValue) *SuperValue {
	this.Path.Superior = this //指向当前对象
	if len(this.kArray) <= index {
		for i := 0; i <= index+1-len(this.kArray); i++ {
			this.kArray = append(this.kArray, *NewSVObject()) //增加零值
		}
	}
	this.kArray[index] = val
	return this
}
func (this *SuperValue) ValueByName(key string) *SuperValue {
	if index := InArray(this.Kys, key); index != -1 {
		return &this.KObj[index].Val
	}
	return nil
}
func (this *SuperValue) ValueByIndex(index int) *SuperValue {
	if len(this.kArray)-1 < index {
		return nil
	}
	return &this.kArray[index]
}
func (this *SuperValue) StringByName(key string, def string) string {
	if this.ValueByName(key) == nil {
		return def
	}
	return this.ValueByName(key).String()
}
func (this *SuperValue) AsStringByIndex(index int, def string) string {
	if this.ValueByIndex(index) == nil {
		return def
	}
	return this.ValueByIndex(index).String()
}
func (this *SuperValue) RemoveFile(file string) *SuperValue {
	//从索引中移除下标相同的元素
	for i, v := range this.Kys {
		if v == file {
			this.Kys = append(this.Kys[:i], this.Kys[i+1:]...)
			this.KObj = append(this.KObj[:i], this.KObj[i+1:]...)
		}
	}
	return this
}

// 用于过滤对象或数组生成一个副本
func (this *SuperValue) Filter(filter func(key string, val *SuperValue) bool) *SuperValue {
	res := NewSVObject()
	switch this.Type {
	case ArrV:
		this.Range(func(key string, val *SuperValue) bool {
			if filter(key, val) {
				res.ArrayAppendValue(val)
			}
			return true
		})
	case ObjV:
		this.Range(func(key string, val *SuperValue) bool {
			if filter(key, val) {
				res.SetKeyValue(key, val)
			}
			return true
		})
	default:
		return this
	}

	return res
}

// 指定键值统计总和和数量
func (this *SuperValue) TotalByFilterSV(filter func(string, *SuperValue) bool) (float64, float64) {
	if this.Type != ObjV && this.Type != ArrV {
		return 0, 0
	}
	s, n := .0, .0
	this.Range(func(key string, val *SuperValue) bool {
		if filter(key, val) {
			s += val.Float64()
			n++
		}
		return true
	})
	return s, n
}

// 使用分号分割
func (this *SuperValue) RemoveFiles(files string) *SuperValue {
	for _, v := range strings.Split(files, ";") {
		this.RemoveFile(v)
	}
	return this
}

// 更改键的名称，值不变
func (this *SuperValue) ChangeName(new string, old string) *SuperValue {
	for i := 0; i < len(this.Kys); i++ {
		if this.Kys[i] == old {
			this.Kys[i] = new
			this.KObj[i].Key = new
		}
	}
	return this
}

func (this *SuperValue) AsArrayByName(key string) *SuperValue {
	s := this.ValueByName(key)
	if s == nil || s.Type != ArrV {
		return NewSVArray()
	}
	return s
}

// 遍历,数组返回下标和值，对象返回键值
func (this *SuperValue) Range(opera func(key string, val *SuperValue) bool) {
	if this.Type == ObjV {
		for i := 0; i < len(this.KObj); i++ {
			if !opera(this.KObj[i].Key, &this.KObj[i].Val) {
				break
			}
		}
	} else if this.Type == ArrV {
		for i := 0; i < len(this.kArray); i++ {
			if !opera(fmt.Sprintf("%d", i), &this.kArray[i]) {
				break
			}
		}
	}
}

// 将当前的字符串拆分成一个字符型数组，如果不为字符串则直接返回
func (this *SuperValue) Split(tag string) *SuperValue {
	if this.Type != StrV {
		return this
	}
	arr := strings.Split(this.Value.(string), tag)
	this.Value = nil
	this.SetValue(arr)
	return this
}

// 将数组转化为字符串
func (this *SuperValue) Join(tag string) *SuperValue {
	if this.Type != ArrV {
		return this
	}
	this.Value = strings.Join(this.AsArrayList(), tag)
	this.Type = StrV
	this.kArray = nil
	return this
}
func (this *SuperValue) RemoveIndexFile(index int) *SuperValue {
	if index > len(this.kArray)-1 || index < 0 {
		return this
	}
	temp := this.kArray[index+1:]    //移除当前位置的元素
	for i := 0; i < len(temp); i++ { //后续元素位置-1
		temp[i].Path.Index-- //需要同时修改其在上级中的位置和下级指向的额元素
	}
	this.kArray = append(this.kArray[:index], temp...)
	for i := 0; i < len(this.kArray); i++ {
		v := this.kArray[i]
		if v.Type == ObjV || v.Type == ArrV { //内部元素仍然引用原数组中的变量，必须清除
			v.Range(func(key string, val *SuperValue) bool {
				val.Path.Superior = &v
				return true
			})
		}
	}
	return this
}
func (this *SuperValue) JsonParseFromByte(byt []byte) error {
	var data interface{}
	decoder := json.NewDecoder(bytes.NewReader(byt))
	decoder.UseNumber()
	decoder.Decode(&data)
	err := this.SetKvData(data)
	if err != nil {
		return err
	}
	return nil
}
func (this *SuperValue) SetKvData(val interface{}) error {
	switch s := val.(type) {
	case map[string]interface{}:
		json.Marshal(s)
		this.Type = ObjV
		for key, pic := range s { //顺序无法保证
			switch pic.(type) {
			case map[string]interface{}, []interface{}:
				this.SetKeyValue(key, NewSVObject())
				s := this.ValueByName(key)
				s.SetKvData(pic) //递归
			default:
				this.SetKeyValue(key, pic)
			}
		}
	case []interface{}:
		this.Type = ArrV
		for _, pic := range s {
			switch pic.(type) {
			case map[string]interface{}, []interface{}:
				this.ArrayAppendValue(NewSVObject())
				s := this.ValueByIndex(len(this.kArray) - 1)
				s.SetKvData(pic) //递归
			default:
				this.ArrayAppendValue(pic)
			}
		}
	default:
		this.Value = val
	}
	return nil
}
func (this *SuperValue) ArrayAppendValue(val interface{}) *SuperValue {
	return this.SetIndexValue(len(this.kArray), val)
}

// 允许添加任意类型的数组或者一个supervalue
func (this *SuperValue) ArrayAppendAll(val interface{}) *SuperValue {
	if this.Type != ArrV {
		return this
	}
	temp := NewSVArray().SetValue(val)
	if temp.Type != ArrV {
		return this
	}
	temp.Range(func(key string, val *SuperValue) bool {
		this.ArrayAppendValue(val)
		return true
	})
	return this
}

func (this *SuperValue) ArrayAppendValues(values ...interface{}) *SuperValue {
	for i := 0; i < len(values); i++ {
		this.ArrayAppendValue(values[i])
	}
	return this
}
func (this *SuperValue) DataTimeByName(key string, def time.Time) time.Time {
	t := def
	s1 := this.ValueByName(key)
	if s1 == nil {
		return t
	}
	s := s1.String()
	layouts := []string{"2006-01-02 15:04:05", "2006/01/02 15:04:05", "20060102", "2006-01-02", "2006/01/02"}
	for _, v := range layouts {
		rs, err := time.ParseInLocation(v, s, time.Local)
		if v == "2006-01-02" {
			fmt.Println(v, s, rs)
		}
		if err == nil {
			t = rs
			break
		}
	}
	return t
}
func (this *SuperValue) IndexFromStrAV(key string) int {
	if this.Type != ArrV {
		return -1
	}
	return InArray(this.AsArrayList(), key)
}
func (this *SuperValue) JsonParseFromFile(path string) error {
	file, err := os.ReadFile(path)
	if err != nil {
		fmt.Println(err.Error())
		return err
	}
	this.JsonParseFromByteEX(file)
	return nil
}

// 若当前值为对象,则返回键的数量,若为数组或字符串，则返回其长度，否则返回0
func (this *SuperValue) Length() int {
	switch this.Type {
	case ObjV:
		return len(this.Kys)
	case ArrV:
		return len(this.kArray)
	case StrV:
		return len(this.Value.(string))
	default:
		return 0
	}
}

// 试用分号进行分割
func (this *SuperValue) ForcePath(key string) *SuperValue {
	if key == "" {
		fmt.Println("请指定路径")
	}
	keys := strings.Split(key, ";")
	res := this
	for _, v := range keys {
		if res.ValueByName(v) == nil {
			res.SetKeyValue(v, NewSVObject())
		}
		res = res.ValueByName(v)
	}
	return res
}

// 使用下标获取键值
func (this *SuperValue) KeyNameByIndex(index int) string {
	if this.Type != ObjV {
		return ""
	}
	if this.Length() <= index {
		return ""
	}
	return this.Kys[index]
}

/*
合并一个对象或者一个数组，对象键名重复时会被覆盖
*/
func (this *SuperValue) Merge(i interface{}) *SuperValue {
	s := *this
	cp := &s
	//cp.JsonParseFromByteEX([]byte(this.String()))
	//错误的写法 cp := *this  注意this中的参数包含指针，该指针不会跟随新的变量而重置，内部指针指向的上级是this的上级
	value := reflect.ValueOf(i)
	//if value.Kind()==reflect.Ptr{   //指针转化为对应的值
	//	value=value.Elem()
	//}
	for value.Kind() == reflect.Ptr { //如果是指针一直转化,直至不为指针
		value = value.Elem()
	}
	if !value.IsValid() {
		fmt.Println("无效指针")
		return this
	}
	switch value.Kind() {
	//填充数据
	case reflect.Array, reflect.Slice:
		if this.Type != ArrV {
			fmt.Println("不是一个数组")
			return nil
		}
		for i := 0; i < value.Len(); i++ {
			cp.ArrayAppendValue(value.Index(i).Interface())
		}
		return cp
		//直接合并全部键值
	case reflect.Map:
		if this.Type != ObjV {
			fmt.Println("不是一个对象")
			return nil
		}
		keys := value.MapKeys()
		for _, key := range keys {
			v := value.MapIndex(key)
			cp.SetKeyValue(fmt.Sprintf("%v", key.Interface()), v.Interface())
		}
		return cp
		//直接合并全部键值
	case reflect.Struct:
		switch s := i.(type) {
		case SuperValue:
			switch s.Type {
			case ObjV:
				if this.Type != ObjV {
					return nil
				}
				//合并两个对象
				s.Range(func(key string, val *SuperValue) bool {
					cp.SetKeyValues(key, val)
					return true
				})
				return cp
			case ArrV:
				if this.Type != ArrV {
					return nil
				}
				//合并两个数组
				cp.kArray = append(cp.kArray, s.kArray...)
				return cp
			default:
				return nil
			}
		case *SuperValue:
			switch s.Type {
			case ObjV:
				if this.Type != ObjV {
					return nil
				}
				//合并两个对象
				s.Range(func(key string, val *SuperValue) bool {
					cp.SetKeyValues(key, val)
					return true
				})
				return cp
			case ArrV:
				if this.Type != ArrV {
					return nil
				}
				//合并两个数组
				cp.kArray = append(cp.kArray, s.kArray...)
				return cp
			default:
				return nil
			}
		default:
			if this.Type != ObjV {
				fmt.Println("不是一个对象")
				return nil
			}
			typ := value.Type()
			for i := 0; i < value.NumField(); i++ {
				name := typ.Field(i).Name
				val := value.Field(i)
				if unicode.IsLower([]rune(name)[0]) {
					fmt.Println("不可访问的值")
					continue
				}
				cp.SetKeyValue(name, val.Interface())
			}
			return cp
		}
	}

	return nil
}
func (this *SuperValue) Total() float64 { //返回一个字段的全部值之和
	if this.Type != ArrV && this.Type != ObjV {
		return 0
	}
	total := 0.0
	this.Range(func(key string, val *SuperValue) bool {
		total += val.Float64()
		return true
	})
	return total
}

func (this *SuperValue) TotalByKey(kys string) float64 { //对象的下一级为数组
	if this.Type != ObjV { //如果当前不为一个对象
		return 0
	}
	return this.ValueByName(kys).Total()
}
func (this *SuperValue) Float64() float64 {
	f, err := strconv.ParseFloat(this.String(), 64)
	if err != nil {
		return 0
	}
	return f
}

/*
按指定精度返回浮点型
*/
func (this *SuperValue) ABS() float64 {
	return math.Abs(this.Float64())
}

func (this *SuperValue) Int8() int8 {
	return int8(this.Int())
}
func (this *SuperValue) Uint() uint {
	return uint(this.Int())
}
func (this *SuperValue) Uint8() uint8 {
	return uint8(this.Int())
}
func (this *SuperValue) Unit32() uint32 {
	return uint32(this.Int())
}

func (this *SuperValue) Uint64() uint64 {
	return uint64(this.Int())
}
func (this *SuperValue) Float32() float32 {
	f, err := strconv.ParseFloat(this.String(), 32)
	if err != nil {
		return 0
	}
	return float32(f)
}
func (this *SuperValue) Int32() int32 {
	return int32(this.Int())
}
func (this *SuperValue) Int64() int64 {
	return int64(this.Int())
}
func (this *SuperValue) Bool(def bool) bool {
	b, err := strconv.ParseBool(this.String())
	if err != nil {
		fmt.Println("Failed to parse bool:", err)
		return def
	}
	return b
}

func (this *SuperValue) IntByName(key string, def int) int {
	aa := this.ValueByName(key)
	if aa == nil {
		return def
	}
	return aa.Int()
}

func (this *SuperValue) Int32ByName(key string, def int32) int32 {
	aa := this.ValueByName(key)
	if aa == nil {
		return def
	}
	return aa.Int32()
}

func (this *SuperValue) Int64ByName(key string, def int64) int64 {
	aa := this.ValueByName(key)
	if aa == nil {
		return def
	}
	return aa.Int64()
}

func (this *SuperValue) Float64ByName(key string, def float64) float64 {
	aa := this.ValueByName(key)
	if aa == nil {
		return def
	}
	return aa.Float64()
}

func (this *SuperValue) Float32ByName(key string, def float32) float32 {
	aa := this.ValueByName(key)
	if aa == nil {
		return def
	}
	return aa.Float32()
}

func (this *SuperValue) BoolByName(key string, def bool) bool {
	aa := this.ValueByName(key)
	if aa == nil {
		return def
	}
	return aa.Bool(def)
}

func (this *SuperValue) AsIntByIndex(index int, def int) int {
	aa := this.ValueByIndex(index)
	if aa == nil {
		return def
	}
	return aa.Int()
}

func (this *SuperValue) AsInt32ByIndex(index int, def int32) int32 {
	aa := this.ValueByIndex(index)
	if aa == nil {
		return def
	}
	return aa.Int32()
}

func (this *SuperValue) AsInt64ByIndex(index int, def int64) int64 {
	aa := this.ValueByIndex(index)
	if aa == nil {
		return def
	}
	return aa.Int64()
}

func (this *SuperValue) AsFloat64ByIndex(index int, def float64) float64 {
	aa := this.ValueByIndex(index)
	if aa == nil {
		return def
	}
	return aa.Float64()
}

func (this *SuperValue) AsFloat32ByIndex(index int, def float32) float32 {
	aa := this.ValueByIndex(index)
	if aa == nil {
		return def
	}
	return aa.Float32()
}

func (this *SuperValue) AsDatatimeByIndex(index int, def time.Time) time.Time {
	t := def
	s1 := this.ValueByIndex(index)
	if s1 == nil {
		return t
	}
	s := s1.String()
	layouts := []string{"2006-01-02 15:04:05", "2006/01/02 15:04:05", "20060102", "2006-01-02", "2006/01/02"}
	for _, v := range layouts {
		rs, err := time.ParseInLocation(v, s, time.Local)
		if v == "2006-01-02" {
			fmt.Println(v, s, rs)
		}
		if err == nil {
			t = rs
			break
		}
	}
	return t
}

func (this *SuperValue) SearchFilesEX(value interface{}) *SuperValue {
	aa := NewSVObject()
	aa.SetValue(value)
	return this.SearchFiles(aa)
}

func (this *SuperValue) SearchFiles(files *SuperValue) *SuperValue {
	var res *SuperValue
	switch this.Type {
	case ObjV:
		this.Range(func(key string, val *SuperValue) bool {
			res = val.SearchFiles(files)
			if res != nil {
				return false
			}
			return true
		})
	case ArrV:
		this.Range(func(key string, val *SuperValue) bool {
			if val.IsEqua(files) {
				res = val
				return false
			} else {
				res = val.SearchFiles(files)
				if res == nil {
					return true
				}
				return false
			}
		})
	default:
		return nil

	}
	return res
}
func (this *SuperValue) SearchKeysEx(key string, value interface{}) *SuperValue {
	aa := NewSVObject().SetValue(value) //将value转化为supervalue
	return this.SearchKeys(key, aa)
}

func (this *SuperValue) GetFirstValue() *SuperValue { //获取数组第一个元素，或者
	//获取数组中的第一个元素或获取对象中的第一个键值
	if this.Type == ArrV {
		if len(this.kArray) == 0 {
			return nil
		}
		return &this.kArray[0]
	} else if this.Type == ObjV {
		if len(this.Kys) == 0 {
			return nil
		}
		return &this.KObj[0].Val
	}
	return nil
}
func (this *SuperValue) GetLastValue() *SuperValue {
	if this.Type == ArrV {
		if len(this.kArray) == 0 {
			return nil
		}
		return &this.kArray[len(this.kArray)-1]
	} else if this.Type == ObjV {
		if len(this.Kys) == 0 {
			return nil
		}
		return &this.KObj[len(this.Kys)-1].Val
	}
	return nil
}

// 去重当前的数组,无论内部元素是对象还是其他数组结构,该操作将直接改变原数组
func (this *SuperValue) DedupArry() *SuperValue {
	if this.Type != ArrV {
		fmt.Println("数据结构不为数组")
		return this
	}
	newArr := []SuperValue{}
	for _, v := range this.kArray {
		state := 0
		for _, s := range newArr {
			if s.IsEquaEx(v) {
				state = 1
			}
		}
		if state == 0 {
			newArr = append(newArr, v)
		}
	}
	this.kArray = newArr
	return this
}

func (this *SuperValue) Max(def float64, filter func(float64) bool) float64 {
	Max := def
	Set := false
	this.Range(func(key string, val *SuperValue) bool {
		f, err := strconv.ParseFloat(val.String(), 64)
		if err == nil {
			if !Set {
				if filter != nil {
					if filter(f) {
						Max = f
						Set = true
					}
				} else {
					Max = f
					Set = true
				}

			} else {
				if f > Max {
					if filter != nil {
						if filter(f) {
							Max = f
						}
					} else {
						Max = f
					}
				}
			}
		}
		return true
	})
	return Max
}

// 返回数组或键值对中的最小值
func (this *SuperValue) Min(def float64, filter func(float64) bool) float64 {
	Min := def
	Set := false
	this.Range(func(key string, val *SuperValue) bool {
		f, err := strconv.ParseFloat(val.String(), 64)
		if err == nil {
			if !Set {
				if filter != nil {
					if filter(f) {
						Min = f
						Set = true
					}
				} else {
					Min = f
					Set = true
				}

			} else {
				if f < Min {
					if filter != nil {
						if filter(f) {
							Min = f
						}
					} else {
						Min = f
					}
				}
			}
		}
		return true
	})
	return Min
}

// 获取一个对象数组中某个键值对的总和
func (this *SuperValue) TotalFromArrKey(keyfile string) float64 {
	if this.Type != ArrV {
		return 0
	}
	tal := .0
	this.Range(func(key string, val *SuperValue) bool {
		tal += val.Float64ByName(keyfile, 0)
		return true
	})
	return tal
}

func (this *SuperValue) AverageFromArrKey(keyfile string) float64 {
	return this.TotalFromArrKey(keyfile) / float64(this.Length())
}

func (this *SuperValue) Average() float64 {
	if this.Length() == 0 {
		return 0
	}
	return this.Total() / float64(this.Length())
}

// 按字典顺序重新排列数组或者按
//func (this *SuperValue) Sort() *SuperValue { //区分当前为数组还是对象,从小到大排列
//	switch this.Type {
//	case ArrV:
//		sort.Slice(this.kArray, func(i, j int) bool {
//			return this.kArray[i].String() < this.kArray[j].String()
//		})
//		//重新设置path的下标
//		for i := 0; i < len(this.kArray); i++ {
//			this.kArray[i].Path.Index = i
//		}
//	case ObjV:
//		//重新排列对象字段
//		sort.Strings(this.Kys)
//		//重新排列数组字段
//		sort.Slice(this.KObj, func(i, j int) bool {
//			return this.KObj[i].Key < this.KObj[j].Key
//		})
//		for i := 0; i < len(this.KObj); i++ {
//			this.KObj[i].Val.Path.Key = this.KObj[i].Key
//		}
//	default:
//
//	}
//	return this
//}

// 根据指定顺序排列数组
func (this *SuperValue) Sort(less func(key1, key2 string, val1, val2 SuperValue) bool) *SuperValue {
	//i,j依次为数组中前面的一个值和后面的一个值
	if this.Type == ArrV {
		for i := 0; i < this.Length()-1; i++ {
			for j := i + 1; j < this.Length(); j++ {
				m := this.kArray[i]      //前者
				n := this.kArray[j]      //后者
				if !less("", "", m, n) { //如果前者小于后者，交换两者之间的值
					this.kArray[i], this.kArray[j] = this.kArray[j], this.kArray[i] //交换两者的值
				}
			}
		}
		//重排数组下标顺序
		for i := 0; i < len(this.kArray); i++ {
			this.kArray[i].Path.Index = i
		}
	} else if this.Type == ObjV {
		for i := 0; i < this.Length(); i++ {
			for j := i + 1; j < this.Length(); j++ {
				key1 := this.Kys[i]
				key2 := this.Kys[j]
				val1 := this.KObj[i].Val
				val2 := this.KObj[j].Val
				if !less(key1, key2, val1, val2) {
					this.Kys[i], this.Kys[j] = this.Kys[j], this.Kys[i]
					this.KObj[i], this.KObj[j] = this.KObj[j], this.KObj[i]
				}
			}
		}
	}
	return this
}

// 获取数组中某个元素的数量
func (this *SuperValue) GetValueCnt(value interface{}) int {
	count := 0
	this.Range(func(key string, val *SuperValue) bool {
		if val.IsEquaEx(value) {
			count++
		}
		return true
	})
	return count
}

// 查找 key的值为value的对象,当查找对象的数据较多时禁用
func (this *SuperValue) SearchKeys(keys string, value *SuperValue) *SuperValue {
	var res *SuperValue
	switch this.Type {
	case ObjV:
		//对象，查找
		this.Range(func(key string, val *SuperValue) bool {
			if key != keys || !val.IsEqua(value) {
				res = val.SearchKeys(keys, value) //找不到则继续找
				if res == nil {
					return true
				}
				return false
			} else { //如果相等
				res = val //找到后直接返回
				return false
			}
		})
	case ArrV:
		//数组去下级查找
		this.Range(func(key string, val *SuperValue) bool {
			res = val.SearchKeys(keys, value)
			if res != nil {
				return false
			}
			return true
		})
	default:
		return nil

	}
	return res
}

// 返回上级,当set了一个supervalue的值后调用此方法处理异常
func (this *SuperValue) Super() *SuperValue {
	if this == nil {
		return nil
	}
	return this.Path.Superior
}

// 清空
func (this *SuperValue) Clear() {
	//清空当前数据
	switch this.Type {
	case ArrV:
		this.kArray = []SuperValue{} //清空
	case ObjV:
		this.KObj = []KvData{}
		this.Kys = []string{}
	default:
		this.Value = nil
	}
	this.Path = Path{} //清空指向的上级
}

// 使用缓存初始化svarray
func NewSVArrayCache(cache bool) *SuperValue {
	if cache {
		//首先从syncpool中获取
		s := ValueCachePool.Get()
		if s != nil {
			return s.(*SuperValue) //如果存在直接返回
		} else {
			return &SuperValue{
				Cache: true,
				Type:  ArrV,
				Path:  Path{},
			}
		}
	}
	return NewSVArray()
}

//调用clear方法不再使用，如果此时cache为true，则将其回收

// 判定是否相等
func (this *SuperValue) IsEqua(compare *SuperValue) bool {
	if this.Type != compare.Type || this.Length() != compare.Length() { //类型不相同时直接返回false
		return false
	}
	//判断类型
	switch this.Type {
	case ArrV:
		//依次比较数组中每个值是否相同
		for i := 0; i < this.Length(); i++ {
			item := this.ValueByIndex(i)
			if !item.IsEqua(compare.ValueByIndex(i)) {
				return false
			}
		}
		return true
	case ObjV:
		//依次比较结构体中的每个值是否相同,无序
		for i := 0; i < len(this.KObj); i++ {
			item := this.KObj[i]
			pic := compare.ValueByName(item.Key)
			if pic == nil {
				return false
			}
			if !item.Val.IsEqua(pic) {
				return false
			}
		}
		return true
	case NumV: //如果两者均为数值，则比较两者的float64型
		aa, _ := strconv.ParseFloat(this.String(), 64)
		bb, _ := strconv.ParseFloat(compare.String(), 64)
		if aa == bb {
			return true
		}
		return false
	default: //其他类型直接比较两者的value
		if this.Value != compare.Value {
			return false
		}
		return true
	}
}

func (this *SuperValue) IsEquaEx(compare interface{}) bool {
	item := NewSVObject().SetValue(compare)
	return this.IsEqua(item)
}

// 以json为桥梁，将一个SuperValue转化为wrapper.Supervalue
//func (this *SuperValue) ToWrapVal() *wrapper.SuperValue {
//	data := wrapper.NewSVObject()
//	data.JsonParserFromByte(this.Byte(false))
//	return data
//}
//
//// 注释这两个函数,解除对wrapper的引用
//func (this *SuperValue) FromWrapVal(data *wrapper.SuperValue) *SuperValue {
//	this.JsonParseFromByteEX([]byte(data.String()))
//	return this
//}

const (
	KeySta = "json_key"
	ValSta = "json_value"
	UndSta = "json_undefined"
)

// 异常信息处理
func (this *SuperValue) HandleErr(s string) error {
	return fmt.Errorf("解析到%s处发生错误", s[0:int(math.Min(15, float64(len(s))))])
}

//func (this *SuperValue) HandleErrEx(s []byte)error{
//	//查找一个完整的中文字符
//	return fmt.Errorf("解析到%s处发生错误", s[0:int(math.Min(8, float64(len(s))))])
//}

// 获取全部键值
func (this *SuperValue) GetKeys() []string {
	if this.Type != ObjV {
		return []string{}
	}
	return this.Kys
}

// 以字节数组的形式获取当前值   true 尝试将数值型数组直接转化为字节数组,当不满足uint8条件时，返回空字节数组,false将当前值作为字符串转化为字节
func (this *SuperValue) Byte(direct bool) []byte {
	if direct {
		if this.Type == ArrV {
			aa := []byte{}
			state := 1
			this.Range(func(key string, val *SuperValue) bool {
				if val.Type == NumV {
					if val.Int() > 255 {
						state = -1
						return false
					}
					aa = append(aa, uint8(val.Int()))
					return true
				}
				state = -1
				return false
			})
			if state == -1 {
				return []byte{}
			}
			return aa
		}
		return []byte{}
	}
	return []byte(this.String())
}

// 将json中转义字符进行转义处理
func (this *SuperValue) DecodeStr(str string) string {
	res := ""
	for i := 0; i < len(str); i++ {
		switch str[i : i+1] {
		case "\\":
			res += `\\`
		case "\n":
			res += `\n` //\\n
		case "\b":
			res += `\b`
		case "\t":
			res += `\t`
		case "\f":
			res += `\f`
		case "\r":
			res += `\r`
		case "\"":
			res += `\"`
		default:
			res += str[i : i+1]
		}

	}
	return res
}

//测试版v3 使用字节切片优化了处理速度

func (this *SuperValue) JsonParseFromByteEX(byt []byte) error {
	if len(byt) == 0 {
		return nil
	}
	this.Clear()     //必须清空,以免造成参数混乱
	PState := ValSta //初始状态
	del := byt
	s := this
	var err error
	for {
		switch PState {
		case KeySta:
			del, PState, s, err = s.jsonParseKeyEX(del)
			if err != nil {
				this.Clear()
				return err
			}
		case ValSta:
			del, PState, s, err = s.jsonParseValueEX(del)
			if err != nil {
				this.Clear()
				return err
			}
		case UndSta:
			del, PState, s, err = s.jsonParseUndefinedEX(del)
			if err != nil {
				this.Clear()
				return err
			}
		}
		if del == nil || len(del) == 0 {
			//fmt.Println(del) //终止状态
			break
		}
		if s == nil { //已经结束解析,但字符串未完整解析
			this.Clear()
			return this.HandleErr(string(del))
		}
	}
	return nil
}

//键状态
/*
未处理转义字符
\"：双引号
\'：单引号
\\：反斜杠
\n：换行符
\r：回车符
\t：制表符
\b：退格符
\f：换页符
*/
func (this *SuperValue) jsonParseKeyEX(s []byte) ([]byte, string, *SuperValue, error) {
	s = bytes.TrimSpace(s)
	SetByte := []byte{}
	//如何寻找键值
	if s[0] != '"' { //第一个值必须是引号
		return []byte{}, "", nil, this.HandleErr(string(s))
	}
	//寻找第二个键值的位置
	for i := 1; i < len(s); i++ {
		switch s[i] {
		//如果是\n
		case '\\':
			if i+1 == len(s) {
				return []byte{}, "", nil, this.HandleErr(string(s))
			}
			switch s[i+1] {
			case '\\':
				SetByte = append(SetByte, '\\')
				i++
			case 't':
				SetByte = append(SetByte, '\t')
				i++
			case 'b':
				SetByte = append(SetByte, '\b')
				i++
			case 'r':
				SetByte = append(SetByte, '\r')
				i++
			case 'f':
				SetByte = append(SetByte, '\f')
				i++
			case 'n':
				SetByte = append(SetByte, '\n')
				i++
			case '"':
				SetByte = append(SetByte, '"')
				i++
			case 'u': // **************重点部分
				if i+5 >= len(s) {
					return []byte{}, "", nil, this.HandleErr(string(s))
				}
				i += 2
				var r rune
				for j := 0; j < 4; j++ {
					//读取4个字符
					if s[i] >= '0' && s[i] <= '9' {
						r = r<<4 + rune(s[i]-'0')
					} else if s[i] >= 'a' && s[i] <= 'f' {
						r = r<<4 + rune(s[i]-'a'+10)
					} else if s[i] >= 'A' && s[i] <= 'F' {
						r = r<<4 + rune(s[i]-'A'+10)
					} else {
						return []byte{}, "", nil, this.HandleErr(string(s))
					}
					i++
				}
				i--
				setlen := len(SetByte)
				SetByte = append(SetByte, 0, 0, 0, 0)
				newstr := utf8.EncodeRune(SetByte[setlen:], r)
				if newstr < 4 {
					SetByte = SetByte[:setlen+newstr]
				}
			default:
				return []byte{}, "", nil, this.HandleErr(string(s))
			}
		//	终止符
		case '"':
			if i+1 == len(s) {
				return []byte{}, "", nil, this.HandleErr(string(s))
			}
			s = bytes.TrimSpace(s[i+1:])
			if s[0] != ':' {
				return []byte{}, "", nil, this.HandleErr(string(s))
			}
			//fmt.Println(s[1:])
			this.SetKeyValue(string(SetByte), "")
			return s[1:], ValSta, this.ValueByName(string(SetByte)), nil
		case '\n':
			return []byte{}, "", nil, this.HandleErr(string(s))
		default:
			SetByte = append(SetByte, s[i])
		}
	}
	return []byte{}, "", nil, this.HandleErr(string(s))
}

// 值状态
func (this *SuperValue) jsonParseValueEX(s []byte) ([]byte, string, *SuperValue, error) {
	s = bytes.TrimSpace(s)
	SetByte := []byte{}
	switch s[0] {
	case '"':
		//查找第二个非转义的”,获取位置
		for i := 1; i < len(s); i++ {
			switch s[i] {
			//如果是\n
			case '\\':
				if i+1 == len(s) {
					return []byte{}, "", nil, this.HandleErr(string(s))
				}

				switch s[i+1] {
				case '\\':
					SetByte = append(SetByte, '\\')
					i++
				case 't':
					SetByte = append(SetByte, '\t')
					i++
				case 'b':
					SetByte = append(SetByte, '\b')
					i++
				case 'r':
					SetByte = append(SetByte, '\r')
					i++
				case 'f':
					SetByte = append(SetByte, '\f')
					i++
				case 'n':
					SetByte = append(SetByte, '\n')
					i++
				case '"':
					SetByte = append(SetByte, '"')
					i++
				case 'u': // **************重点部分
					if i+5 >= len(s) { //必须有足够的字符来促成unicode码点
						return []byte{}, "", nil, this.HandleErr(string(s))
					}
					i += 2
					var r rune
					for j := 0; j < 4; j++ { //少于4个字符将报错
						//fmt.Println(string(s[i]))
						//sl:=rune(s[i])
						//读取4个字符

						if s[i] >= '0' && s[i] <= '9' {
							r = r<<4 + rune(s[i]-'0')
						} else if s[i] >= 'a' && s[i] <= 'f' {
							r = r<<4 + rune(s[i]-'a'+10)
						} else if s[i] >= 'A' && s[i] <= 'F' {
							r = r<<4 + rune(s[i]-'A'+10)
						} else {
							return []byte{}, "", nil, this.HandleErr(string(s))
						}
						i++
					}
					//5-6个字符
					for j := 0; j < int(math.Min(2, float64(len(s)-i))); j++ {
						if s[i] >= '0' && s[i] <= '9' && r<<4+rune(s[i]-'0') <= 1114111 {
							r = r<<4 + rune(s[i]-'0')
						} else if s[i] >= 'a' && s[i] <= 'f' && r<<4+rune(s[i]-'a'+10) <= 1114111 {
							r = r<<4 + rune(s[i]-'a'+10)
						} else if s[i] >= 'A' && s[i] <= 'F' && r<<4+rune(s[i]-'F'+10) <= 1114111 {
							r = r<<4 + rune(s[i]-'A'+10)
						} else {
							break
						}
						i++
					}
					//fmt.Println(r)
					i--
					setlen := len(SetByte)
					SetByte = append(SetByte, 0, 0, 0, 0)
					newstr := utf8.EncodeRune(SetByte[setlen:], r)
					if newstr < 4 {
						SetByte = SetByte[:setlen+newstr]
					}
				default:
					return []byte{}, "", nil, this.HandleErr(string(s))
				}
			//	终止符
			case '"':
				this.Type = StrV
				this.Value = string(SetByte)
				if i == len(s)-1 && this.Super() == nil {
					return []byte{}, UndSta, this.Super(), nil
				}
				return s[i+1:], UndSta, this.Super(), nil
			case '\n':
				return []byte{}, "", nil, this.HandleErr(string(s))
			default:
				SetByte = append(SetByte, s[i])
			}
		}
		return []byte{}, "", nil, this.HandleErr(string(s))
	case 'f':
		if string(s[0:5]) != "false" {
			return []byte{}, "", nil, this.HandleErr(string(s))
		}
		this.Type = BoolV
		this.Value = false
		return s[5:], UndSta, this.Super(), nil
	case 't':
		if string(s[0:4]) != "true" {
			return []byte{}, "", nil, this.HandleErr(string(s))
		}
		this.Type = BoolV
		this.Value = true
		return s[4:], UndSta, this.Super(), nil
	case 'n':
		if string(s[0:4]) != "null" {
			return []byte{}, "", nil, this.HandleErr(string(s))
		}
		this.Type = NumV
		this.Value = "null"
		return s[4:], UndSta, this.Super(), nil
	case '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '-':
		target := ""
		point, ex := false, false
		if s[0] == '-' {
			//第二位不为数字
			if !bytes.Contains([]byte("0123456789"), s[1:2]) {
				return []byte{}, "", nil, this.HandleErr(string(s))
			} else {
				target = "-"
				s = s[1:]
			}
		}
		if s[0] == '0' && s[1] != '.' { //如果第一位为0,
			this.Type = NumV
			this.Value = string(s[0:1])
			return s[1:], UndSta, this.Super(), nil
		} else {
			//查找第一个不为数字的字符串
			instr := []byte("0123456789.")
			for i := 1; i < len(s); i++ {
				if !bytes.Contains(instr, s[i:i+1]) {
					if i <= len(s)-3 && (bytes.Contains([]byte("e+"), s[i:i+2]) || bytes.Contains([]byte("e-"), s[i:i+2])) && !ex {
						i += 2
						ex = true
						//continue
					} else {
						this.Type = NumV
						this.Value = target + string(s[0:i])
						return s[i:], UndSta, this.Super(), nil
					}
				} else if this.Super() == nil && i == len(s)-1 {
					this.Type = NumV
					this.Value = target + string(s)
					return []byte{}, UndSta, this.Super(), nil
				}
				if s[i] == '.' { //只允许一个小数点
					if point {
						return []byte{}, "", nil, this.HandleErr(string(s))
					}
					point = true
				}
			}
		}
	case '{':
		this.Type = ObjV
		return s[1:], UndSta, this, nil
	case '[':
		this.Type = ArrV
		return s[1:], UndSta, this, nil
	default:
		return []byte{}, "", nil, this.HandleErr(string(s))
	}
	return []byte{}, "", nil, this.HandleErr(string(s))
}

// 待定状态   字串，异常状态
func (this *SuperValue) jsonParseUndefinedEX(s []byte) ([]byte, string, *SuperValue, error) {
	//忽略空白字符串
	s = bytes.TrimSpace(s)
	switch this.Type {
	case ArrV:
		if s[0] == ']' {
			return s[1:], UndSta, this.Super(), nil //退出，返回上一级
		} else if this.Length() == 0 {
			this.SetIndexValue(this.Length(), "")
			item := this.ValueByIndex(this.Length() - 1)
			return s, ValSta, item, nil //进入值状态
		} else if s[0] == ',' {
			this.SetIndexValue(this.Length(), "")
			item := this.ValueByIndex(this.Length() - 1)
			return s[1:], ValSta, item, nil //进入值状态
		} else {
			return []byte{}, "", nil, this.HandleErr(string(s))
		}
	case ObjV:
		if s[0] == '}' {
			return s[1:], UndSta, this.Super(), nil
		} else if this.Length() == 0 {
			return s, KeySta, this, nil
		} else if s[0] == ',' {
			return s[1:], KeySta, this, nil
		} else {
			return []byte{}, "", nil, this.HandleErr(string(s))
		}
	default:
		return []byte{}, "", nil, this.HandleErr(string(s))
	}
}

// 如果当前为一个json字符串，则将其转化为对象
func (this *SuperValue) FormJsonData() error {
	if this.Type != StrV {
		return fmt.Errorf("指定键值不是一个字符串")
	}
	//fmt.Println(this.String())
	//fmt.Println(this.String())
	return this.JsonParseFromByteEX([]byte(this.String()))
}

// 将一个对象数组或一个对象中指定的键值转为supervalue
func (this *SuperValue) FormDatas(keys ...string) error {
	if len(keys) == 0 {
		return fmt.Errorf("未指定键值")
	}
	if this.Type == ArrV {
		this.Range(func(key string, val *SuperValue) bool {
			if val.Type == ObjV {
				for _, v := range keys {
					temp := val.ValueByName(v)
					if temp != nil {
						err := temp.FormJsonData()
						if err != nil {
							fmt.Println(val.ValueByName(v))
							fmt.Println(err.Error())
							return false
						}
					}
				}
			}
			return true
		})
		return nil
	} else if this.Type == ObjV {
		for _, v := range keys {
			temp := this.ValueByName(v)
			if temp != nil {
				temp.FormJsonData() //依次对选定的数据格式化
			}
		}
	}
	return fmt.Errorf("数据格式既不是数组也不是对象")
}

// 不改变原数据  对象为数组时使用此方法可以将数组按指定的键值组合进行划分,返回一个划分的完整对象和每个组合中的第一条数据
func (this *SuperValue) DivKDatas(keys string, concat string, ignore int, need int) (*SuperValue, *SuperValue) {
	res := NewSVObject()
	onlres := NewSVArray()
	keyarray := strings.Split(keys, ",")
	this.Range(func(key string, val *SuperValue) bool {
		str := ""
		for _, v := range keyarray {
			str += val.StringByName(v, "") + concat

		}
		str = strings.TrimRight(str, concat)
		if res.ValueByName(str) == nil {
			res.SetKeyValue(str, NewSVArray())
			res.ValueByName(str).ArrayAppendValue(val)
			if ignore > 0 {
				ignore--
			} else if need > 0 || need == -1 {
				onlres.ArrayAppendValue(val)
				if need > -1 {
					need--
				}
			}
		} else {
			res.ValueByName(str).ArrayAppendValue(val)
		}
		return true
	})
	return res, onlres
}

// 将supervalue转化为一个基本类型
func (this *SuperValue) Interface() interface{} {
	//将其转变为基本类型
	switch this.Type {
	case ArrV: //数组
		return this.ToInterfaceArr()
	case ObjV: //map
		return this.ToInterfaceMap()
	default: //其他类型
		return this.Value
	}
}

func (this *SuperValue) ToInterfaceArr() []interface{} {
	res := []interface{}{}
	this.Range(func(key string, val *SuperValue) bool {
		res = append(res, val.Interface())
		return true
	})
	return res
}

func (this *SuperValue) ToInterfaceMap() map[string]interface{} {
	res := make(map[string]interface{})
	this.Range(func(key string, val *SuperValue) bool {
		res[key] = val.Interface()
		return true
	})
	return res
}

// 快速生成指定字段的副本
func (this *SuperValue) EsyCopy(arg ...string) *SuperValue {
	res := NewSVObject()
	for _, v := range arg {
		if index := InArray(this.Kys, v); index >= 0 {
			res.Kys = append(res.Kys, v)
			res.KObj = append(res.KObj, this.KObj[index])
		}
	}
	return res
}

func NewSVObjByKeyValues(KV ...interface{}) *SuperValue {
	temp := &SuperValue{Path: Path{}, Type: ObjV}
	temp.SetKeyValues(KV...)
	return temp
}

func NewSVArrayByDatas(Datas ...interface{}) *SuperValue {
	temp := &SuperValue{Path: Path{}, Type: ArrV}
	temp.ArrayAppendValues(Datas...)
	return temp
}

/*
读取指定的文件,将其中的每一列转化为SVArray中的一项

	BDT                C19_A    C19_C    C19_R  C19_CLK  C19_ORB  C19_SIS    C19

2023/10/06 00:00:00   0.1233  -0.1586  -0.0238  -0.5785   0.0360   0.5558      0
*/
func NewSVArrayFromFile(path string, titleline, dataline int, gettitle func(str string) []string, setdata func(line int, str string) []string) (*SuperValue, error) {
	if gettitle == nil || setdata == nil {
		return nil, fmt.Errorf("未指定标题和文件的处理方式")
	}
	file, err := os.Open(path)
	if err != nil {
		return nil, err
	}
	defer file.Close()
	scanner := bufio.NewScanner(file)
	keyfiles := []string{}
	if titleline < 0 {
		keyfiles = gettitle("")
	}
	line := 1
	data := NewSVArray()
	for scanner.Scan() {
		if line == titleline {
			keyfiles = gettitle(scanner.Text())
		}
		if line >= dataline {
			item := setdata(line, scanner.Text())
			if item == nil {
				line++
				continue
			}
			if len(item) != len(keyfiles) {
				return nil, fmt.Errorf("标题栏和数据栏长度不对应")
			}
			pic := NewSVObject()
			for i, v := range item {
				pic.SetKeyValue(keyfiles[i], v)
			}
			data.ArrayAppendValue(pic)
		}
		line++
	}
	return data, nil
}

// 从csv二进制流中读取文件
func NewSVArrayFromCSVReader(reader *csv.Reader, titleline, dataline int, gettitle func(str []string) []string, setdata func(line int, str []string) []string) (*SuperValue, error) {
	keyfiles := []string{}
	if titleline < 0 {
		if gettitle == nil {
			return nil, fmt.Errorf("gettitle is undefined")
		}
		keyfiles = gettitle(nil)
	}
	line := 1
	data := NewSVArray()
	for {
		s, err := reader.Read()
		if err != nil {
			break
		}
		if line == titleline {
			keyfiles = s
			if gettitle != nil {
				keyfiles = gettitle(s) //标题行
			}
		}
		if line >= dataline {
			item := s
			if setdata != nil {
				item = setdata(line, s) //每一行的数据
				if item == nil {
					line++
					continue
				}
			}
			if item == nil {
				line++
				continue
			}
			if len(item) != len(keyfiles) {
				return nil, fmt.Errorf("标题栏和数据栏长度不对应")
			}
			pic := NewSVObject()
			for i, v := range item {
				pic.SetKeyValue(keyfiles[i], v)
			}
			data.ArrayAppendValue(pic)
		}
		line++
	}
	return data, nil
}

// 从excel二进制文件中初始化一个sv,注意reader需要关闭
//func NewSVArrayFromXlsxReader(reader *excel.File, sheet string, titleline, dataline int, gettitle func(str []string) []string, setdata func(line int, str []string) []string) (*SuperValue, error) {
//	data := NewSVArray()
//	var title []string
//	if titleline < 1 {
//		if gettitle == nil {
//			return nil, fmt.Errorf("gettitle is undefined")
//		} else {
//			title = gettitle(nil)
//		}
//	}
//	rows, err := reader.Rows(sheet)
//	if err != nil {
//		fmt.Println(err.Error())
//		return nil, err
//	}
//	defer rows.Close() //注意关闭
//	line := 1
//	for rows.Next() {
//		r, err := rows.Columns()
//		if err != nil {
//			fmt.Println(err.Error())
//			break
//		}
//		if line == titleline {
//			if gettitle != nil {
//				title = gettitle(r)
//			} else {
//				title = r
//			}
//		}
//		if line >= dataline {
//			value := r
//			if setdata != nil {
//				value = setdata(line, r)
//				if value == nil {
//					line++
//					continue
//				}
//			}
//			item := NewSVObject()
//			for i, v := range value {
//				item.SetKeyValue(title[i], v)
//			}
//			data.ArrayAppendValues(item)
//		}
//		line++
//	}
//	return data, nil
//}

// 将数组对象转化为excel
//func (this *SuperValue) SaveAsXlsx(filepath string, stylefunc func(*excel.File), title ...interface{}) (string, error) {
//	if this.Type != ArrV {
//		return "", fmt.Errorf("不是一个数组")
//	}
//	if this.Length() == 0 {
//		return "", fmt.Errorf("数据为空")
//	}
//	reg := regexp.MustCompile(`(.*/)?[^/]+$`)
//	res := reg.FindAllStringSubmatch(filepath, -1)
//	if len(res) == 0 {
//		return "", fmt.Errorf("请指正确的文件路径")
//	}
//	//空白文件
//	file := excel.NewFile()
//	defer func() {
//		if err := file.Close(); err != nil {
//			fmt.Println(err.Error())
//		}
//	}()
//	//设置表名
//	file.SetSheetName("Sheet1", "sheet1")
//	//创建流式写入
//	writer, er := file.NewStreamWriter("sheet1")
//	if er != nil {
//		return "", er
//	}
//	//修改列宽
//	writer.SetColWidth(1, 10, 20)
//	//设置标题
//	titl := title
//	if len(title) == 0 {
//		for _, v := range this.ValueByIndex(0).Kys {
//			titl = append(titl, v)
//		}
//	}
//
//	writer.SetRow("A1", titl)
//	if stylefunc != nil {
//		stylefunc(file)
//	}
//	for i := 0; i < this.Length(); i++ {
//		//先切换至下一行   若未切换则写入停留在第一行，最后保存第二行的数据为空，第一行的数据未保存不会被修改
//		cell, _ := excel.CoordinatesToCellName(1, i+2)
//		item := this.ValueByIndex(i)
//		sfile := []interface{}{}
//		item.Range(func(key string, val *SuperValue) bool {
//			sfile = append(sfile, val)
//			return true
//		})
//		writer.SetRow(cell, sfile)
//	}
//	if res[0][1] != "" {
//		err := os.MkdirAll(res[0][1], 0777)
//		if err != nil {
//			fmt.Println(err.Error())
//			return "", err
//		}
//	}
//	writer.Flush()
//	err := file.SaveAs(filepath)
//	if err != nil {
//		fmt.Println(err.Error())
//		return "", err
//	}
//	return filepath, nil
//
//}

// 读取excel并生成supervalue
//func NewSVArrayFromXlsxFile(path, sheet string, titleline, dataline int, gettitle func([]string) []string, setdata func(int, []string) []string) (*SuperValue, error) {
//	file, err := excel.OpenFile(path, excel.Options{})
//	defer file.Close()
//	if err != nil {
//		return nil, err
//	}
//	return NewSVArrayFromXlsxReader(file, sheet, titleline, dataline, gettitle, setdata)
//	//rows, _ := file.Rows(sheet)
//	//defer rows.Close()
//	//if err != nil {
//	//	return nil, err
//	//}
//	//line := 1
//	//tmp := NewSVArray()
//	//for rows.Next() { //下一行
//	//	if title == nil && line == 1 {
//	//		title, err = rows.Columns()
//	//		fmt.Println(title)
//	//		if err != nil {
//	//			return nil, err
//	//		}
//	//		line++
//	//		continue
//	//	}
//	//	row, err := rows.Columns()
//	//	if err != nil {
//	//		return nil, err
//	//	}
//	//	if len(row) > len(title) {
//	//		return nil, fmt.Errorf("数据长度大于标题长度")
//	//	}
//	//	item := NewSVObject()
//	//	for i, v := range row {
//	//		item.SetKeyValue(title[i], v)
//	//	}
//	//	tmp.ArrayAppendValue(item)
//	//	line++
//	//}
//	//return tmp, nil
//}

// 保存为标题+数据的文本格式报存
//
//	func (this *SuperValue) SaveAsFile(path string, title []string, split string) error {
//		if this.Type != ArrV {
//			return fmt.Errorf("数据格式不正确")
//		}
//		if this.Length() == 0 {
//			return fmt.Errorf("数据不能为空")
//		}
//		s := strings.Split(path, "/")
//		if len(s) != 1 {
//			err := os.MkdirAll(strings.Join(s[:len(s)-1], "/"), 0777)
//			if err != nil {
//				return err
//			}
//		}
//
//		file, err := os.OpenFile(path, os.O_CREATE|os.O_RDWR|os.O_TRUNC, 0777)
//		defer file.Close()
//		if err != nil {
//			return err
//		}
//		if title == nil {
//			title = this.ValueByIndex(0).Kys
//		}
//		file.WriteString(strings.Join(title, split) + "\n")
//		this.Range(func(key1 string, val1 *SuperValue) bool {
//			str := ""
//			val1.Range(func(key string, val *SuperValue) bool {
//				str += val.String() + split
//				return true
//			})
//			str = strings.TrimSuffix(str, split)
//			file.WriteString(str + "\n")
//			return true
//		})
//		return nil
//	}
func (this *SuperValue) SaveAsFile(path string, withtitle bool, title []string, split string, trunc bool, datalen ...string) error {
	if this.Type != ArrV {
		return fmt.Errorf("数据格式不正确")
	}
	if this.Length() == 0 {
		return fmt.Errorf("数据不能为空")
	}
	s := strings.Split(path, "/")
	if len(s) != 1 {
		err := os.MkdirAll(strings.Join(s[:len(s)-1], "/"), 0777)
		if err != nil {
			return err
		}
	}
	mode := os.O_CREATE | os.O_RDWR | os.O_APPEND
	if trunc {
		mode = os.O_CREATE | os.O_RDWR | os.O_TRUNC
	}
	file, err := os.OpenFile(path, mode, 0777)
	defer file.Close()
	if err != nil {
		return err
	}
	//标题写入
	defarr := make([]string, len(this.ValueByIndex(0).Kys))
	if len(datalen) != 0 {
		defarr = datalen
	} else {
		for i := 0; i < len(defarr); i++ {
			defarr[i] = "20"
		}
	}

	if withtitle {
		if title == nil {
			title = this.ValueByIndex(0).Kys
		}
		tit := ""
		for i, v := range title {
			tit += fmt.Sprintf("%-"+defarr[i]+"s", v) + split
			//tit += fmt.Sprintf("%-20s", v)
		}
		tit = strings.TrimSuffix(tit, split)
		tit += "\n"
		file.WriteString(tit)
	}

	this.Range(func(key1 string, val1 *SuperValue) bool {
		str := ""
		i := 0
		val1.Range(func(key string, val *SuperValue) bool {
			str += fmt.Sprintf("%-"+defarr[i]+"s", val.String()) + split
			//str += fmt.Sprintf("%-20s", val.String())
			i++
			return true
		})
		str = strings.TrimSuffix(str, split)
		file.WriteString(str + "\n")
		return true
	})
	return nil
}

// 将当前数据以json的形式报存
func (this *SuperValue) SaveJsonString(path string) error {
	s := strings.Split(path, "/")
	if len(s) != 1 {
		err := os.MkdirAll(strings.Join(s[:len(s)-1], "/"), 0777)
		if err != nil {
			return err
		}
	}
	file, _ := os.OpenFile(path, os.O_CREATE|os.O_TRUNC|os.O_RDWR, 0777)
	defer file.Close()
	_, err := file.WriteString(this.String())
	if err != nil {
		return err
	}
	return nil
}

// 以当前数据发送post请求
//
//	func (this *SuperValue) Post(url string) *SuperValue {
//		res, err := PostV2(url, Json+UTF8, this.String(), nil, nil, nil)
//		if err != nil {
//			fmt.Println(err.Error())
//			return nil
//		}
//		return res
//	}
func (this *SuperValue) Child(start int, end int) *SuperValue {
	if this.Type != ArrV && this.Type != StrV { //不为字符串和数组时直接返回
		fmt.Println("不是一个数组或字符串")
		return this
	}
	res := NewSVArray()
	if this.Type == ArrV {
		res.kArray = this.kArray[start:end] //子切片
	} else {
		res.Type = StrV
		res.Value = this.Value.(string)[start:end]
	}
	return res
}

// 将当前数组批量插入数据库,主键重复时可选择更新,当指定位置的keys设置为空时，将不更新或者插入此字段
//func (this *SuperValue) Insert(DateBase string, table string, keys []string, replace bool) error {
//	if this.Type != ArrV && this.Type != ObjV {
//		return fmt.Errorf("必须是一个数组或对象")
//	}
//	if this.Length() == 0 {
//		return fmt.Errorf("数组或对象长度为0")
//	}
//	title := keys
//	if title == nil {
//		if this.Type == ObjV {
//			title = this.Kys
//		} else {
//			title = this.ValueByIndex(0).Kys
//		}
//	}
//	ignore := ""
//	if !replace {
//		ignore = "ignore "
//	}
//	sql := fmt.Sprintf("insert %sinto %s(%s) values", ignore, table, strings.Join(title, ","))
//	if this.Type == ObjV {
//		pic := ""
//		this.Range(func(key string, val *SuperValue) bool {
//			pic += fmt.Sprint("'", val, "',")
//			return true
//		})
//		pic = strings.TrimSuffix(pic, ",")
//		sql += fmt.Sprintf("(%s)", pic)
//	} else {
//		this.Range(func(key1 string, val1 *SuperValue) bool {
//			pic := ""
//			val1.Range(func(key2 string, val2 *SuperValue) bool {
//				pic += fmt.Sprint("'", val2, "',")
//				return true
//			})
//			pic = strings.TrimSuffix(pic, ",")
//			sql += fmt.Sprintf("(%s),", pic)
//			return true
//		})
//		sql = strings.TrimSuffix(sql, ",")
//	}
//	if replace {
//		sql += " ON DUPLICATE KEY UPDATE "
//		for _, v := range title {
//			sql += fmt.Sprint(v, "=values(", v, "),")
//		}
//		sql = strings.TrimSuffix(sql, ",")
//	}
//	fmt.Println(sql)
//	dao := PrjDBUtils.NewDAOHelperEx(DateBase, "")
//	defer dao.Close()
//	err := dao.PrepareDBConn()
//	if err != nil {
//		fmt.Println(err.Error())
//		return err
//	}
//	if _, err = dao.DBConn.Exec(sql); err != nil {
//		return err
//	}
//	return nil
//}

// 检查obj中指定键值是否存在,不存在时,可以从创建
func (this *SuperValue) CheckKeysExists(Keys string, create func(string) interface{}) bool {
	exist := true
	for _, v := range strings.Split(Keys, ";") {
		if this.ValueByName(v) == nil {
			exist = false
			if create(v) != nil {
				this.SetKeyValue(v, create(v))
			}
		}
	}
	return exist
}

/*
转化前
{
"a":1,
"b":2,
"c":3
}
使用ReName方法

	data.ReName(func(m map[string]string) {
		m["a"] = "as"
		m["b"] = "bs"
	})

转化后
{
"as":1,
"bs":2,
"c":3
}
*/
func (this *SuperValue) ChangValueName(Namefunc func(map[string]string)) *SuperValue {
	if this.Type != ObjV || Namefunc == nil {
		return this
	}
	KeyMap := map[string]string{}
	for _, v := range this.Kys {
		KeyMap[v] = v //添加
	}
	Namefunc(KeyMap) //注意确保唯一性
	var Check []string
	for _, val := range KeyMap {
		Check = append(Check, val)
	}
	if len(Check) != NewSVArray().SetValue(Check).DedupArry().Length() {
		fmt.Println("键名重复")
		return this
	}
	for i, v := range this.Kys {
		this.Kys[i] = KeyMap[v]
		this.KObj[i].Key = KeyMap[v]
	}
	return this
}

// 向数组或字符串中添加任意参数
func (this *SuperValue) Add(val interface{}) *SuperValue {
	switch this.Type {
	case ArrV:
		this.ArrayAppendValue(val)
	case StrV:
		this.Value = this.Value.(string) + fmt.Sprintf("%v", val)
	}
	return this
}
func (this *SuperValue) RegExpCheck(regstr string) bool {
	reg := regexp.MustCompile(regstr)
	return reg.MatchString(this.String())
}
func (this *SuperValue) RegExpFindStr(regstr string) [][]string {
	reg := regexp.MustCompile(regstr)
	//reg.ReplaceAllStringFunc()
	return reg.FindAllStringSubmatch(this.String(), -1)
}

// 强制转化为string类型,并替换其中的值
func (this *SuperValue) RegExpReplace(regstr string, repl func(string) string) {
	reg := regexp.MustCompile(regstr)
	str := reg.ReplaceAllStringFunc(this.String(), repl)
	this.Type = StrV
	this.Value = str
}

// 返回指定参数在数组中的位置，参数可以是任意基本或引用类型
func (this *SuperValue) Index(s interface{}) int {
	index := -1
	if this.Type != ArrV {
		return index
	}
	target := NewSVObject().SetValue(s)
	for i := 0; i < this.Length(); i++ {
		val := this.ValueByIndex(i)
		if val.IsEqua(target) { //不使用IsEquaEX,减少不必要的性能浪费
			index = i
			break
		}
	}
	return index
}

// 将原本的对象，转化成一个由键值组成大的数组
func (this *SuperValue) GetValueList() *SuperValue {
	res := NewSVArray()
	this.Range(func(key string, val *SuperValue) bool {
		res.ArrayAppendValue(val)
		return true
	})
	return res
}

// 通过下标获取键值名称
func (this *SuperValue) GetKeyNameByIndex(index int) string {
	return this.Kys[index]
}

/*
使用当前的数据创建数据库表格

	str := `{
	  "id":123,              ==>int(0)
	  "money":123.01,        ==>decimal(20,2)
	  "msg":"msg",           ==>varchar(225)/text(0)
	  "Date":"2023/06/07"    ==>datetime(0)
	 }`
		data := NewSVArray()
		data.JsonParseFromByteEX([]byte(str))
		isbn:="root:Kpl@kplcors412!!!B%@tcp(119.96.145.175:3306)/cloud_vrs?charset=utf8&parseTime=true&loc=Local"
		data.CreateTable(isbn, "Mytest", "id;money", true)
*/
//func (this *SuperValue) CreateTable(isbn string, TableName string, PRIMARY string, drop bool) error {
//	sql := "SET NAMES utf8mb4;SET FOREIGN_KEY_CHECKS = 0;"
//	if drop {
//		sql += fmt.Sprintf("DROP TABLE IF EXISTS `%s`;CREATE TABLE `%s`  (", TableName, TableName)
//	} else {
//		sql += fmt.Sprintf("CREATE TABLE IF NOT EXISTS `%s`  (", TableName)
//	}
//	regt := regexp.MustCompile(`(?:\d{4}-\d{2}-\d{2}|\d{4}/\d{2}/\d{2})(?:\s+\d{2}:\d{2}:\d{2})?`)
//	this.Range(func(key string, val *SuperValue) bool {
//		pic := "NULL DEFAULT NULL,"
//		if strings.Contains(PRIMARY, key) {
//			pic = "NOT NULL,"
//		}
//		switch val.Type {
//		case NumV:
//			if strings.Contains(val.String(), ".") {
//				sql += fmt.Sprintf("`%s` decimal(20, %d) %s\n", key, len(strings.Split(val.String(), ".")[1]), pic)
//			} else {
//				sql += fmt.Sprintf("`%s` int(0) %s\n", key, pic)
//			}
//		case StrV:
//			if regt.MatchString(val.String()) {
//				sql += fmt.Sprintf("`%s` datetime(0) %s\n", key, pic)
//			} else {
//				if val.Length() < 200 { //根据参数选择合适的长度
//					sql += fmt.Sprintf("`%s` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci  %s\n", key, pic)
//				} else {
//					sql += fmt.Sprintf("`%s` text CHARACTER SET utf8 COLLATE utf8_general_ci NULL,", key)
//				}
//
//			}
//		default:
//			//其他类型均采用varchar
//			sql += fmt.Sprintf("`%s` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci  %s\n", key, pic)
//		}
//		return true
//	})
//	if PRIMARY != "" {
//		pic := ""
//		for _, v := range strings.Split(PRIMARY, ";") {
//			pic += fmt.Sprintf("`%s`,", v)
//		}
//		pic = strings.TrimSuffix(pic, ",")
//		sql += fmt.Sprintf(" PRIMARY KEY (%s) USING BTREE", pic)
//	} else {
//		sql = strings.TrimSuffix(sql, ",\n")
//	}
//	sql += ") ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;SET FOREIGN_KEY_CHECKS = 1"
//	fmt.Println(sql)
//	db, err := mysql.Open("mysql", isbn)
//	if err != nil {
//		return err
//	}
//	defer db.Close()
//	tx, err := db.Begin()
//	if err != nil {
//		return err
//	}
//	for _, l := range strings.Split(sql, ";") {
//		_, err = tx.Exec(l)
//		if err != nil {
//			tx.Rollback()
//			return err
//		}
//	}
//	//执行完毕
//	tx.Commit()
//	return nil
//}
func RoundFloat64(val float64, tag int) float64 {
	if tag > 0 {
		val = math.Round(val*math.Pow10(tag)) / math.Pow10(tag)
	} else if tag < 0 {
		tag = -tag
		val = math.Round(val/math.Pow10(tag)) * math.Pow10(tag)
	} else {
		val = math.Round(val)
	}
	return val
}

func CeilFloat64(val float64, tag int) float64 {
	if tag > 0 {
		val = math.Ceil(val*math.Pow10(tag)) / math.Pow10(tag)
	} else if tag < 0 {
		tag = -tag
		val = math.Ceil(val/math.Pow10(tag)) * math.Pow10(tag)
	} else {
		val = math.Ceil(val)
	}
	return val
}

func FloorFloat64(val float64, tag int) float64 {
	if tag > 0 {
		val = math.Floor(val*math.Pow10(tag)) / math.Pow10(tag)
	} else if tag < 0 {
		tag = -tag
		val = math.Floor(val/math.Pow10(tag)) * math.Pow10(tag)
	} else {
		val = math.Floor(val)
	}
	return val
}

func (this *SuperValue) Round(tag int) float64 {
	return RoundFloat64(this.Float64(), tag)
}

func (this *SuperValue) Ceil(tag int) float64 {
	return CeilFloat64(this.Float64(), tag)
}

func (this *SuperValue) Floor(tag int) float64 {
	return FloorFloat64(this.Float64(), tag)
}

func (this *SuperValue) RoundByName(key string, tag int) float64 {
	return this.ValueByName(key).Floor(tag)
}

func (this *SuperValue) CeilByName(key string, tag int) float64 {
	return this.ValueByName(key).Ceil(tag)
}

func (this *SuperValue) FloorByName(key string, tag int) float64 {
	return this.ValueByName(key).Floor(tag)
}

/*
Delayer
[{"id":1,"name":"444"},{"id":2,"name":"333"}]  =>{"id":[1,2],"name":["444","333"]}
*/
func (this *SuperValue) Delayer() *SuperValue {
	//将重复的键值转化为数组
	list := NewSVObject()
	if this.Type != ArrV || this.Length() == 0 {
		return list
	}

	for _, v := range this.ValueByIndex(0).Kys {
		list.SetKeyValue(v, NewSVArray())
	}
	this.Range(func(key string, val *SuperValue) bool {
		val.Range(func(key2 string, val2 *SuperValue) bool {
			s := list.ValueByName(key2)
			if s == nil {
				fmt.Println("数据字段不匹配")
				return false
			}
			s.ArrayAppendValues(val2)
			return true
		})
		return true
	})
	return list
}

func (this *SuperValue) SortEX(less func(key1, key2 string, val1, val2 SuperValue) bool) *SuperValue {
	//i,j依次为数组中前面的一个值和后面的一个值
	if this.Type == ArrV {
		sort.Slice(this.kArray, func(i, j int) bool {
			return less("", "", this.kArray[i], this.kArray[j])
		})
	} else if this.Type == ObjV {
		sort.Slice(this.KObj, func(i, j int) bool {
			return less(this.Kys[i], this.Kys[j], this.KObj[i].Val, this.KObj[j].Val)
		})
		this.Kys = []string{}
		for _, v := range this.KObj { //重排键名
			this.Kys = append(this.Kys, v.Key)
		}
	}
	return this
}
